// DOM元素
const sidebar = document.getElementById('sidebar');
const mainContent = document.getElementById('main-content');
const toggleSidebarBtn = document.getElementById('toggle-sidebar');
const mobileToggleSidebarBtn = document.getElementById('mobile-toggle-sidebar');
const userSidebar = document.getElementById('user-sidebar');
const userAvatar = document.getElementById('user-avatar');
const overlay = document.getElementById('overlay');
const userInputEl = document.getElementById('user-input');
const sendBtnEl = document.getElementById('send-btn');
const chatMessagesEl = document.getElementById('chat-messages');
const typingIndicatorEl = document.getElementById('typing-indicator');
const statusIndicatorEl = document.getElementById('status-indicator');
const conversationListEl = document.getElementById('conversation-list');
const emptyHistoryEl = document.getElementById('empty-history');
const newChatText = document.getElementById('new-chat-text');
const sidebarTitle = document.getElementById('sidebar-title');
const currentConversationTitleEl = document.getElementById('current-conversation-title');
const emptyChatStateEl = document.getElementById('empty-chat-state');
const modelSelectEl = document.getElementById('model-select');
const currentModelBadgeEl = document.getElementById('current-model-badge');
const typingModelTextEl = document.getElementById('typing-model-text');

// 状态变量
let eventSource = null;
let currentConversationId = null;
let currentConversationTitle = 'AI 聊天';
let currentSessionId = null;
let conversations = [];
let isSidebarCollapsed = false;
let currentModel = 'deepseek'; // 默认模型
let isStreaming = false;
let stopRequested = false;
let currentRequestId = null;

// 模型配置
const modelConfig = {
    deepseek: {
        name: 'DeepSeek',
        badgeClass: 'deepseek'
    },
    baidu: {
        name: '文心一言',
        badgeClass: 'baidu'
    },
    qwen: {
        name: '通义千问',
        badgeClass: 'qwen'
    }
};

// 新的消息渲染系统
class MessageRenderer {
    constructor() {
        this.isStreaming = false;
        this.currentStreamingMessage = null;
    }

    // 添加用户消息
    addUserMessage(message) {
        this.removeEmptyState();

        const messageEl = this.createMessageElement('user');
        const contentEl = this.createContentElement();

        // 用户消息直接显示纯文本
        contentEl.textContent = message;
        messageEl.appendChild(contentEl);

        this.addCopyButton(messageEl, message);
        chatMessagesEl.appendChild(messageEl);
        this.scrollToBottom();

        return messageEl;
    }

    // 开始AI消息流式渲染
    startAIStream() {
        this.removeEmptyState();
        this.isStreaming = true;

        const messageEl = this.createMessageElement('ai');
        messageEl.id = 'ai-streaming-message';
        messageEl.classList.add('streaming');

        const contentEl = this.createContentElement();
        messageEl.appendChild(contentEl);

        this.currentStreamingMessage = { element: messageEl, content: '' };
        chatMessagesEl.appendChild(messageEl);
        this.scrollToBottom();

        return messageEl;
    }

// 更新流式消息内容
    updateStreamContent(content) {
        if (!this.currentStreamingMessage || !this.isStreaming) return;

        this.currentStreamingMessage.content = content;
        const contentEl = this.currentStreamingMessage.element.querySelector('.message-content');

        if (contentEl) {
            try {
                // 使用新的Markdown渲染器
                contentEl.innerHTML = this.renderMarkdown(content);

                // 高亮代码块
                this.highlightCodeBlocks(contentEl);

                // 添加复制按钮
                this.addCodeCopyButtons();
            } catch (error) {
                console.error('渲染流式内容失败:', error);
                // 如果渲染失败，显示原始内容
                contentEl.textContent = content;
            }
        }

        this.scrollToBottom();
    }

    // 完成流式渲染
    finishStream() {
        if (!this.currentStreamingMessage) return;

        this.isStreaming = false;
        const messageEl = this.currentStreamingMessage.element;
        messageEl.removeAttribute('id');
        messageEl.classList.remove('streaming');

        const contentEl = messageEl.querySelector('.message-content');
        if (contentEl) {
            // 最终渲染，确保所有格式正确
            contentEl.innerHTML = this.renderMarkdown(this.currentStreamingMessage.content);
            this.highlightCodeBlocks(contentEl);
            this.addCodeCopyButtons();

            // 添加消息复制按钮
            this.addCopyButton(messageEl, this.currentStreamingMessage.content);
        }

        this.currentStreamingMessage = null;
        this.scrollToBottom();
    }

    // 创建消息元素
    createMessageElement(type) {
        const messageEl = document.createElement('div');
        messageEl.className = `message ${type}`;

        const avatarEl = document.createElement('div');
        avatarEl.className = `message-avatar`;
        avatarEl.innerHTML = type === 'user' ?
            '<span>U</span>' :
            '<i class="bi bi-robot"></i>';

        messageEl.appendChild(avatarEl);
        return messageEl;
    }

    // 创建内容元素
    createContentElement() {
        const contentEl = document.createElement('div');
        contentEl.className = 'message-content';
        return contentEl;
    }

    // 移除空状态
    removeEmptyState() {
        const emptyState = chatMessagesEl.querySelector('.empty-state');
        if (emptyState) {
            emptyState.remove();
        }
    }

    // 滚动到底部
    scrollToBottom() {
        setTimeout(() => {
            chatMessagesEl.scrollTop = chatMessagesEl.scrollHeight;
        }, 0);
    }

    // 增强的Markdown渲染
    renderMarkdown(content) {
        if (!content) return '';

        let html = this.escapeHtml(content);

        // 代码块处理（优先）
        html = this.renderCodeBlocks(html);

        // 行内代码和数学公式处理
        html = this.renderInlineCodeAndMath(html);

        // 标题
        html = html.replace(/^### (.*$)/gm, '<h3>$1</h3>');
        html = html.replace(/^## (.*$)/gm, '<h2>$1</h2>');
        html = html.replace(/^# (.*$)/gm, '<h1>$1</h1>');

        // 粗体和斜体
        html = html.replace(/\*\*\*(.*?)\*\*\*/g, '<strong><em>$1</em></strong>');
        html = html.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
        html = html.replace(/\*(.*?)\*/g, '<em>$1</em>');

        // 引用
        html = html.replace(/^> (.*$)/gm, '<blockquote>$1</blockquote>');

        // 无序列表
        html = html.replace(/^\s*[-*+] (.*$)/gm, '<li>$1</li>');
        html = html.replace(/(<li>.*<\/li>)/s, '<ul>$1</ul>');

        // 有序列表
        html = html.replace(/^\s*\d+\. (.*$)/gm, '<li>$1</li>');
        html = html.replace(/(<li>.*<\/li>)(?!\s*<li>)/s, '<ol>$1</ol>');

        // 链接
        html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank">$1</a>');

        // 分割线
        html = html.replace(/^\s*---\s*$/gm, '<hr>');

        // 表格（简化处理）
        html = this.renderTables(html);

        // 段落处理
        html = this.renderParagraphs(html);

        return html;
    }

    // 渲染行内代码和数学公式
    renderInlineCodeAndMath(html) {
        // 处理行内代码 `code`
        html = html.replace(/`([^`]+)`/g, '<code class="inline-code">$1</code>');

        // 处理数学公式和特殊符号
        html = this.renderMathFormulas(html);

        return html;
    }

    // 渲染数学公式和特殊符号
    renderMathFormulas(html) {
        // 匹配数学函数如 log₂(1024)、sin(x)、cos(θ) 等
        html = html.replace(/(\b(log|ln|sin|cos|tan|sqrt|max|min|sum|avg)[₂₃ₙᵢⱼₖₗₘₙ]?\([^)]+\))/g,
            '<code class="math-formula">$1</code>');

        // 匹配C++命名空间如 std::set、std::map 等
        html = html.replace(/(\b[a-z_][a-z0-9_]*::[a-z_][a-z0-9_]*\b)/gi,
            '<code class="inline-code">$1</code>');

        // 匹配数学符号如 α, β, γ, θ, π, ∞, ∑, ∫, ∂, ∇ 等
        html = html.replace(/([αβγδεζηθικλμνξοπρστυφχψω∞∑∫∂∇∆∏√∛∜])/g,
            '<code class="math-formula">$1</code>');

        // 匹配数学表达式如 x², y₃, aⁿ 等上下标
        html = html.replace(/([a-zA-Zα-ω][²³ⁿᵢⱼₖₗₘₙₒₚₓₐₑₕᵢⱼₖₗₘₙₒₚₓ₌₍₎]|[₀₁₂₃₄₅₆₇₈₉])/g,
            '<code class="math-formula">$1</code>');

        // 匹配数学运算符如 ≤, ≥, ≠, ≈, ≡ 等
        html = html.replace(/([≤≥≠≈≡≢≣≦≧≨≩≪≫≬≭≮≯≰≱≲≳≴≵≶≷≸≹≺≻≼≽≾≿⊀⊁⊂⊃⊄⊅⊆⊇⊈⊉⊊⊋⊌⊍⊎⊏⊐⊑⊒⊓⊔⊕⊖⊗⊘⊙⊚⊛⊜⊝⊞⊟⊠⊡])/g,
            '<code class="math-formula">$1</code>');

        return html;
    }

    // 渲染代码块（DeepSeek风格）
    renderCodeBlocks(html) {
        return html.replace(/```(\w+)?\s*\n([\s\S]*?)```/g, (match, language, code) => {
            const lang = language || 'text';
            const escapedCode = this.escapeHtml(code.trim());

            return `
                <div class="code-block-wrapper">
                    <div class="code-block-header">
                        <span class="code-language">${lang}</span>
                        <button class="code-copy-btn" onclick="copyCodeBlock(this)">
                            <i class="bi bi-clipboard"></i>
                            复制代码
                        </button>
                    </div>
                    <div class="code-block-content">
                        <pre><code class="language-${lang} hljs">${escapedCode}</code></pre>
                    </div>
                </div>
            `;
        });
    }

    // 渲染表格
    renderTables(html) {
        const tableRegex = /((?:\|.*\|(?:\r?\n|$))+)/g;
        return html.replace(tableRegex, (match) => {
            const rows = match.trim().split('\n').filter(row => row.trim());
            if (rows.length < 2) return match;

            let tableHtml = '<div class="table-container"><table>';

            rows.forEach((row, index) => {
                const cells = row.split('|').map(cell => cell.trim()).filter(cell => cell);
                if (cells.length === 0) return;

                const isHeader = index === 0;
                const tag = isHeader ? 'th' : 'td';

                tableHtml += '<tr>';
                cells.forEach(cell => {
                    tableHtml += `<${tag}>${cell}</${tag}>`;
                });
                tableHtml += '</tr>';
            });

            tableHtml += '</table></div>';
            return tableHtml;
        });
    }

    // 渲染段落
    renderParagraphs(html) {
        // 将连续的空行转换为段落
        const lines = html.split('\n');
        let inParagraph = false;
        let result = '';

        for (let line of lines) {
            const trimmed = line.trim();

            if (!trimmed) {
                if (inParagraph) {
                    result += '</p>';
                    inParagraph = false;
                }
                result += '<br>';
            } else if (trimmed.startsWith('<') && trimmed.endsWith('>')) {
                // 已经是HTML标签，直接添加
                if (inParagraph) {
                    result += '</p>';
                    inParagraph = false;
                }
                result += line + '\n';
            } else {
                if (!inParagraph) {
                    result += '<p>';
                    inParagraph = true;
                }
                result += line + '\n';
            }
        }

        if (inParagraph) {
            result += '</p>';
        }

        return result;
    }

    // 高亮代码块
    highlightCodeBlocks(container) {
        if (typeof hljs !== 'undefined') {
            container.querySelectorAll('pre code').forEach((block) => {
                // 移除已有的高亮类
                block.className = block.className.replace(/hljs/g, '');
                block.className += ' hljs';

                hljs.highlightElement(block);
            });
        }
    }

    // 添加代码复制按钮
    addCodeCopyButtons() {
        document.querySelectorAll('.code-block-wrapper').forEach(wrapper => {
            const copyBtn = wrapper.querySelector('.code-copy-btn');
            const code = wrapper.querySelector('code').textContent;

            // 移除旧的事件监听器
            const newCopyBtn = copyBtn.cloneNode(true);
            copyBtn.parentNode.replaceChild(newCopyBtn, copyBtn);

            newCopyBtn.addEventListener('click', () => {
                this.copyToClipboard(code, newCopyBtn);
            });
        });
    }

    // 添加消息复制按钮
    addCopyButton(messageEl, content) {
        // 移除已存在的复制按钮
        const existingBtn = messageEl.querySelector('.message-copy-btn');
        if (existingBtn) existingBtn.remove();

        const copyBtn = document.createElement('button');
        copyBtn.className = 'message-copy-btn';
        copyBtn.innerHTML = '<i class="bi bi-clipboard"></i>';
        copyBtn.title = '复制消息';
        copyBtn.onclick = () => {
            this.copyToClipboard(content);
        };
        messageEl.appendChild(copyBtn);
    }

    // 复制到剪贴板
    copyToClipboard(text, button = null) {
        navigator.clipboard.writeText(text).then(() => {
            if (button) {
                const originalHTML = button.innerHTML;
                button.innerHTML = '<i class="bi bi-check"></i> 已复制';
                button.disabled = true;

                setTimeout(() => {
                    button.innerHTML = originalHTML;
                    button.disabled = false;
                }, 2000);
            }
            showStatus('已复制到剪贴板', 'success');
            setTimeout(hideStatus, 2000);
        }).catch(err => {
            console.error('复制失败:', err);
            showStatus('复制失败', 'error');
        });
    }

    // HTML转义
    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    // 清空聊天
    clearChat() {
        chatMessagesEl.innerHTML = `
            <div class="empty-state" id="empty-chat-state">
                <i class="bi bi-robot"></i>
                <h4>${currentConversationId ? currentConversationTitle : '欢迎使用 AI 聊天'}</h4>
                <p>${currentConversationId ? '对话内容已清空' : '开始与AI助手对话吧！'}</p>
            </div>
        `;
    }
}

// 初始化渲染器
const messageRenderer = new MessageRenderer();

// 打开系统设置
function openSettings() {
    const modal = new bootstrap.Modal(document.getElementById('settingsModal'));
    modal.show();
    closeAllSidebars();
}

// 更新账户信息
function updateAccount() {
    const formData = {
        username: document.getElementById('username').value,
        email: document.getElementById('email').value,
        phone: document.getElementById('phone').value,
        currentPassword: document.getElementById('currentPassword').value,
        newPassword: document.getElementById('newPassword').value
    };

    // 调用后端API更新用户信息 - 路径保持不变
    fetch('/api/user/update', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(formData)
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showStatus('账户信息更新成功', 'success');
                setTimeout(() => {
                    location.reload();
                }, 2000);
            } else {
                showStatus('更新失败: ' + data.message, 'error');
            }
        })
        .catch(error => {
            console.error('更新账户信息失败:', error);
            showStatus('更新失败，请重试', 'error');
        });
}

// 清空所有对话
function clearAllConversations() {
    if (!confirm('确定要清空所有对话吗？此操作不可恢复！')) {
        return;
    }

    // 路径保持不变
    fetch('/api/conversations/clear-all', {
        method: 'DELETE'
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showStatus('所有对话已清空', 'success');
                // 清空当前聊天界面
                clearChat();
                // 重新加载对话列表
                loadConversations();
                // 关闭模态框
                bootstrap.Modal.getInstance(document.getElementById('settingsModal')).hide();
            } else {
                showStatus('清空失败: ' + data.message, 'error');
            }
        })
        .catch(error => {
            console.error('清空对话失败:', error);
            showStatus('清空失败，请重试', 'error');
        });
}

// 主题切换功能
function initTheme() {
    const savedTheme = localStorage.getItem('theme') || 'light';
    setTheme(savedTheme);

    // 设置单选按钮状态
    const themeRadio = document.getElementById(savedTheme + 'Theme');
    if (themeRadio) {
        themeRadio.checked = true;
    }

    // 监听主题切换
    document.querySelectorAll('input[name="theme"]').forEach(radio => {
        radio.addEventListener('change', (e) => {
            setTheme(e.target.value);
        });
    });

    // 监听模态框显示事件，确保主题正确应用
    const settingsModal = document.getElementById('settingsModal');
    if (settingsModal) {
        settingsModal.addEventListener('show.bs.modal', function() {
            // 确保模态框内的主题与当前主题一致
            const currentTheme = localStorage.getItem('theme') || 'light';
            setTheme(currentTheme);
        });
    }
}

function setTheme(theme) {
    if (theme === 'dark') {
        document.body.classList.add('dark-theme');
        // 更新模态框内的单选按钮状态
        const darkRadio = document.getElementById('darkTheme');
        const lightRadio = document.getElementById('lightTheme');
        if (darkRadio) darkRadio.checked = true;
        if (lightRadio) lightRadio.checked = false;
    } else {
        document.body.classList.remove('dark-theme');
        // 更新模态框内的单选按钮状态
        const darkRadio = document.getElementById('darkTheme');
        const lightRadio = document.getElementById('lightTheme');
        if (darkRadio) darkRadio.checked = false;
        if (lightRadio) lightRadio.checked = true;
    }
    localStorage.setItem('theme', theme);
}

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    if (!checkLoginStatus()) return;
    initializeSession();
    loadConversations();
    setupEventListeners();
    updateDisplay();
    loadSupportedModels();
    initTheme(); // 初始化主题

    // 初始化代码高亮
    hljs.configure({
        tabReplace: '    ',
        classPrefix: 'hljs-',
        languages: ['javascript', 'python', 'java', 'html', 'css', 'sql', 'bash']
    });
});

// 设置事件监听器
function setupEventListeners() {
    // 切换侧边栏
    toggleSidebarBtn.addEventListener('click', toggleSidebar);
    mobileToggleSidebarBtn.addEventListener('click', toggleMobileSidebar);

    // 发送消息
    userInputEl.addEventListener('keypress', handleKeyPress);

    // 模型选择
    modelSelectEl.addEventListener('change', function(e) {
        changeModel(e.target.value);
        saveSessionState();
    });

    // 页面卸载时关闭连接
    window.addEventListener('beforeunload', cleanup);

    // ESC键停止生成
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape' && isStreaming) {
            e.preventDefault();
            stopStream();
            showStatus('已使用ESC键停止生成', 'info');
        }
    });

    // 输入框自适应高度
    userInputEl.addEventListener('input', function() {
        this.style.height = 'auto';
        this.style.height = Math.min(this.scrollHeight, 200) + 'px';
    });
}

// 处理按键事件
function handleKeyPress(e) {
    if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault();
        startStream();
    }
}

// 切换模型
function changeModel(modelType) {
    if (!modelType || modelType === currentModel) return;

    // 如果当前有对话且不是新对话，检查是否可以切换模型
    if (currentConversationId) {
        // 获取对话详情检查模型
        fetch(`/api/conversations/${currentConversationId}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error('获取对话详情失败');
                }
                return response.json();
            })
            .then(data => {
                // 适应新的API响应格式
                const conversation = data && data.success ? data.data : data;
                if (conversation && conversation.model && conversation.model !== modelType) {
                    // 对话已绑定其他模型，不允许切换
                    showStatus(`该对话已绑定到 ${conversation.model} 模型，无法切换到 ${modelType}`, 'error');
                    // 恢复原来的选择
                    modelSelectEl.value = currentModel;
                    return;
                }

                // 允许切换模型
                performModelChange(modelType);
            })
            .catch(error => {
                console.error('检查对话模型失败:', error);
                // 如果检查失败，允许切换但显示警告
                showStatus('切换模型警告: ' + error.message, 'warning');
                performModelChange(modelType);
            });
    } else {
        // 没有对话或新对话，允许切换
        performModelChange(modelType);
    }
}

// 执行模型切换
function performModelChange(modelType) {
    currentModel = modelType;
    const modelInfo = modelConfig[modelType] || { name: modelType, badgeClass: '' };

    // 更新模型徽章
    currentModelBadgeEl.textContent = modelInfo.name;
    currentModelBadgeEl.className = `model-badge ${modelInfo.badgeClass}`;

    // 更新输入指示器
    typingModelTextEl.textContent = modelInfo.name;

    // 更新选择框的值
    modelSelectEl.value = modelType;

    console.log('切换到模型:', modelType);
    showStatus(`已切换到: ${modelInfo.name}`, 'success');
    setTimeout(hideStatus, 2000);

    // 保存模型选择
    saveSessionState();
}

// 加载支持的模型列表
function loadSupportedModels() {
    // 修改为新的路径
    fetch('/api/ai/models')
        .then(response => {
            if (!response.ok) {
                throw new Error('获取模型列表失败');
            }
            return response.json();
        })
        .then(data => {
            console.log('支持的模型响应:', data);

            // 适应新的API响应格式
            const models = data && data.success ? data.data : data;
            console.log('支持的模型:', models);
            updateModelSelector(models);
        })
        .catch(error => {
            console.error('加载模型列表失败:', error);
        });
}

// 更新模型选择器
function updateModelSelector(models) {
    // 清空现有选项
    modelSelectEl.innerHTML = '';

    // 检查数据结构
    if (models && models.models && Array.isArray(models.models)) {
        // 新的ModelConfigResponse格式
        models.models.forEach(model => {
            if (model.enabled) {
                const option = document.createElement('option');
                option.value = model.code;
                option.textContent = model.name;
                // 设置当前选中的模型
                option.selected = model.code === currentModel;
                modelSelectEl.appendChild(option);
            }
        });
    } else if (Array.isArray(models)) {
        // 旧的数组格式
        models.forEach(model => {
            if (model.enabled) {
                const option = document.createElement('option');
                option.value = model.code;
                option.textContent = model.name;
                // 设置当前选中的模型
                option.selected = model.code === currentModel;
                modelSelectEl.appendChild(option);
            }
        });
    }

    // 确保模型选择器显示正确的模型
    modelSelectEl.value = currentModel;

    // 更新模型显示
    changeModel(currentModel);
}

// 切换侧边栏（桌面端）
function toggleSidebar() {
    if (window.innerWidth <= 768) {
        toggleMobileSidebar();
        return;
    }

    isSidebarCollapsed = !isSidebarCollapsed;
    sidebar.classList.toggle('collapsed', isSidebarCollapsed);

    // 更新图标和文本
    if (isSidebarCollapsed) {
        toggleSidebarBtn.innerHTML = '<i class="bi bi-chevron-right"></i>';
        newChatText.style.display = 'none';
        sidebarTitle.style.display = 'none';
    } else {
        toggleSidebarBtn.innerHTML = '<i class="bi bi-chevron-left"></i>';
        newChatText.style.display = 'inline';
        sidebarTitle.style.display = 'block';
    }
}

// 切换侧边栏（移动端）
function toggleMobileSidebar() {
    sidebar.classList.toggle('open');
    overlay.classList.toggle('active');
}

// 切换用户信息边栏
function toggleUserSidebar() {
    userSidebar.classList.toggle('open');
    overlay.classList.toggle('active');
}

// 关闭所有边栏
function closeAllSidebars() {
    sidebar.classList.remove('open');
    userSidebar.classList.remove('open');
    overlay.classList.remove('active');
}

// 检查登录状态
function checkLoginStatus() {
    // 这里可以添加更详细的登录状态检查
    const userLoggedIn = true; // 假设用户已登录
    if (!userLoggedIn) {
        // 修改为重定向到新的认证路径
        window.location.href = '/auth/login';
        return false;
    }
    return true;
}

// 初始化会话
function initializeSession() {
    // 从localStorage恢复会话状态
    const savedSessionId = localStorage.getItem('currentSessionId');
    const savedConversationId = localStorage.getItem('currentConversationId');
    const savedConversationTitle = localStorage.getItem('currentConversationTitle');
    const savedModel = localStorage.getItem('currentModel');

    if (savedSessionId) {
        currentSessionId = savedSessionId;
    } else {
        currentSessionId = generateSessionId();
        localStorage.setItem('currentSessionId', currentSessionId);
    }

    if (savedConversationId) {
        currentConversationId = savedConversationId;
    }

    if (savedConversationTitle) {
        currentConversationTitle = savedConversationTitle;
    }

    // 优先使用保存的模型，否则使用默认的deepseek
    if (savedModel && modelConfig[savedModel]) {
        currentModel = savedModel;
    } else {
        currentModel = 'deepseek';
    }

    // 设置选择框的值
    modelSelectEl.value = currentModel;

    updateDisplay();
}

// 生成会话ID
function generateSessionId() {
    return 'sess_' + Date.now() + '_' + Math.random().toString(36).substr(2, 8);
}

// 生成请求ID
function generateRequestId() {
    return 'req_' + Date.now() + '_' + Math.random().toString(36).substr(2, 6);
}

// 更新显示
function updateDisplay() {
    currentConversationTitleEl.textContent = currentConversationTitle;

    // 确保模型选择器显示正确的模型
    modelSelectEl.value = currentModel;

    // 更新模型显示
    changeModel(currentModel);
}

// 保存会话状态
function saveSessionState() {
    if (currentSessionId) {
        localStorage.setItem('currentSessionId', currentSessionId);
    }
    if (currentConversationId) {
        localStorage.setItem('currentConversationId', currentConversationId);
    }
    if (currentConversationTitle) {
        localStorage.setItem('currentConversationTitle', currentConversationTitle);
    }
    if (currentModel) {
        localStorage.setItem('currentModel', currentModel);
    }
}

// 加载对话历史
function loadConversations() {
    console.log('开始加载对话历史...');
    // 路径保持不变
    fetch('/api/conversations?page=1&size=100')
        .then(response => {
            if (!response.ok) {
                throw new Error(`获取对话历史失败: ${response.status} ${response.statusText}`);
            }
            return response.json();
        })
        .then(data => {
            console.log('成功加载对话历史:', data);

            // 检查数据结构，适应新的响应格式
            if (data && data.success && data.data) {
                const responseData = data.data;

                // 从 ConversationListResponse 中提取 conversations 数组
                if (responseData.conversations && Array.isArray(responseData.conversations)) {
                    conversations = responseData.conversations.map(conv => ({
                        id: conv.id,
                        title: conv.title,
                        model: conv.model,
                        timestamp: new Date(conv.updateTime || conv.createTime)
                    }));
                    renderConversationList();
                } else {
                    console.warn('对话列表数据结构异常:', responseData);
                    conversations = [];
                    renderConversationList();
                }
            } else {
                console.warn('API响应格式异常:', data);
                conversations = [];
                renderConversationList();
            }
        })
        .catch(error => {
            console.error('加载对话失败:', error);
            showStatus('加载对话历史失败: ' + error.message, 'error');
        });
}

// 渲染对话列表
function renderConversationList() {
    if (conversations.length === 0) {
        emptyHistoryEl.style.display = 'block';
        conversationListEl.style.display = 'none';
        return;
    }

    emptyHistoryEl.style.display = 'none';
    conversationListEl.style.display = 'block';

    let listHTML = '';
    conversations.forEach(conv => {
        const time = conv.timestamp.toLocaleDateString() + ' ' + conv.timestamp.toLocaleTimeString();
        const modelBadge = getModelBadge(conv.model);
        listHTML += `
            <li class="conversation-item ${conv.id === currentConversationId ? 'active' : ''}">
                <div class="conversation-content" onclick="loadConversation(${conv.id}, '${conv.title.replace(/'/g, "\\'")}')">
                    <i class="bi bi-chat-left-text me-2"></i>
                    <div class="conversation-info">
                        <div class="conversation-header">
                            <span class="conversation-title">${conv.title}</span>
                            <span class="conversation-model-badge ${modelBadge.class}">${modelBadge.name}</span>
                        </div>
                        <div class="conversation-footer">
                            <span class="conversation-time">${time}</span>
                        </div>
                    </div>
                </div>
                <button class="delete-conversation-btn" onclick="deleteConversation(${conv.id}, event)">
                    <i class="bi bi-trash"></i>
                </button>
            </li>
        `;
    });

    conversationListEl.innerHTML = listHTML;
}

// 获取模型徽章信息
function getModelBadge(modelType) {
    const modelInfo = modelConfig[modelType] || { name: modelType, badgeClass: '' };
    return {
        name: modelInfo.name,
        class: modelInfo.badgeClass
    };
}

// 删除对话函数
function deleteConversation(conversationId, event) {
    // 阻止事件冒泡，避免触发对话加载
    if (event) {
        event.stopPropagation();
        event.preventDefault();
    }

    // 确认删除
    if (!confirm('确定要删除这个对话吗？删除后无法恢复。')) {
        return;
    }

    console.log('删除对话:', conversationId);

    // 路径保持不变
    fetch(`/api/conversations/${conversationId}`, {
        method: 'DELETE',
        headers: {
            'Content-Type': 'application/json'
        }
    })
        .then(response => {
            if (response.ok) {
                // 从本地列表中移除
                conversations = conversations.filter(conv => conv.id !== conversationId);

                // 如果删除的是当前对话，清空当前对话状态
                if (currentConversationId === conversationId) {
                    currentConversationId = null;
                    currentConversationTitle = 'AI 聊天';
                    saveSessionState();
                    updateDisplay();

                    // 清空聊天区域
                    messageRenderer.clearChat();
                }

                // 重新渲染列表
                renderConversationList();

                showStatus('对话已删除', 'success');
                setTimeout(hideStatus, 2000);
            } else {
                throw new Error('删除失败');
            }
        })
        .catch(error => {
            console.error('删除对话失败:', error);
            showStatus('删除失败: ' + error.message, 'error');
        });
}

// 加载特定对话
function loadConversation(conversationId, conversationTitle) {
    console.log('加载对话:', conversationId, conversationTitle);

    // 先获取对话详情以获取模型信息
    // 路径保持不变
    fetch(`/api/conversations/${conversationId}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('获取对话详情失败');
            }
            return response.json();
        })
        .then(data => {
            console.log('对话详情响应:', data);

            // 适应新的API响应格式
            const conversation = data && data.success ? data.data : data;

            currentConversationId = conversationId;
            currentConversationTitle = conversationTitle;

            // 切换到对话绑定的模型
            if (conversation && conversation.model && conversation.model !== currentModel) {
                changeModel(conversation.model);
            }

            // 保存状态
            saveSessionState();
            updateDisplay();

            // 加载消息
            loadConversationMessages(conversationId);
        })
        .catch(error => {
            console.error('获取对话详情失败:', error);
            // 如果获取详情失败，使用当前模型加载消息
            currentConversationId = conversationId;
            currentConversationTitle = conversationTitle;
            saveSessionState();
            updateDisplay();
            loadConversationMessages(conversationId);
        });
}

// 加载对话消息
function loadConversationMessages(conversationId) {
    // 显示加载状态
    chatMessagesEl.innerHTML = `
        <div class="text-center p-4">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">加载中...</span>
            </div>
            <p class="mt-2 text-muted">正在加载对话内容...</p>
        </div>
    `;

    // 路径保持不变
    fetch(`/api/conversations/${conversationId}/messages`)
        .then(response => {
            if (!response.ok) {
                throw new Error('获取对话消息失败');
            }
            return response.json();
        })
        .then(data => {
            console.log('成功加载消息响应:', data);

            // 适应新的API响应格式
            const messages = data && data.success ? data.data : data;
            console.log('成功加载消息:', messages);

            chatMessagesEl.innerHTML = '';

            if (!messages || messages.length === 0) {
                chatMessagesEl.innerHTML = `
                    <div class="empty-state">
                        <i class="bi bi-chat-left-text"></i>
                        <h4>${currentConversationTitle}</h4>
                        <p>这是一个空的对话</p>
                    </div>
                `;
            } else {
                // 渲染历史消息
                messages.forEach(msg => {
                    if (msg.role === 'assistant' || msg.role === 'ASSISTANT') {
                        // 使用新的渲染器渲染AI消息
                        const messageEl = messageRenderer.startAIStream();
                        messageRenderer.updateStreamContent(msg.content);
                        messageRenderer.finishStream();
                    } else {
                        // 使用新的渲染器渲染用户消息
                        messageRenderer.addUserMessage(msg.content);
                    }
                });
            }

            renderConversationList();
            closeAllSidebars();
            showStatus('对话加载成功', 'success');
            setTimeout(hideStatus, 2000);
        })
        .catch(error => {
            console.error('加载对话消息失败:', error);
            chatMessagesEl.innerHTML = `
                <div class="empty-state">
                    <i class="bi bi-exclamation-triangle"></i>
                    <h4>加载失败</h4>
                    <p>${error.message}</p>
                    <button class="btn btn-primary mt-2" onclick="loadConversation(${conversationId}, '${currentConversationTitle.replace(/'/g, "\\'")}')">重试</button>
                </div>
            `;
            showStatus('加载对话失败: ' + error.message, 'error');
        });
}

// 新建对话
function newConversation() {
    console.log('创建新对话...');
    // 生成新的会话ID
    currentSessionId = generateSessionId();
    currentConversationId = null;
    currentConversationTitle = '新对话';

    // 保存状态但不重置模型
    saveSessionState();
    updateDisplay();

    // 清空聊天区域
    messageRenderer.clearChat();

    showStatus('新对话已创建', 'success');
    setTimeout(hideStatus, 2000);
}

// 开始流式对话
function startStream() {
    if (!checkLoginStatus()) return;

    // 如果正在流式传输，则执行停止操作
    if (isStreaming) {
        stopStream();
        showStatus('已停止生成', 'info');
        return;
    }

    const userMessage = userInputEl.value.trim();

    if (!userMessage) {
        showStatus('请输入消息', 'error');
        return;
    }

    console.log('开始流式对话，模型:', currentModel, {
        userMessage,
        sessionId: currentSessionId,
        conversationId: currentConversationId
    });

    // 如果有对话ID，验证模型是否匹配
    if (currentConversationId) {
        fetch(`/api/conversations/${currentConversationId}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error('获取对话详情失败');
                }
                return response.json();
            })
            .then(data => {
                // 适应新的API响应格式
                const conversation = data && data.success ? data.data : data;
                if (conversation && conversation.model && conversation.model !== currentModel) {
                    showStatus(`该对话已绑定到 ${conversation.model} 模型，请切换到对应模型`, 'error');
                    return;
                }

                // 模型匹配，继续发送消息
                sendMessage();
            })
            .catch(error => {
                console.error('检查对话模型失败:', error);
                // 如果检查失败，继续发送但显示警告
                showStatus('发送消息警告: ' + error.message, 'warning');
                sendMessage();
            });
    } else {
        // 没有对话ID，直接发送消息
        sendMessage();
    }

    function sendMessage() {
        // 生成新的请求ID，防止重复
        currentRequestId = generateRequestId();
        console.log('生成请求ID:', currentRequestId);

        // 使用新的渲染器添加用户消息
        messageRenderer.addUserMessage(userMessage);

        // 重置状态
        hideStatus();
        setButtonState(true, true);
        showTypingIndicator();
        userInputEl.value = '';
        userInputEl.disabled = true; // 禁用输入框
        userInputEl.style.height = 'auto'; // 重置输入框高度

        // 设置流式状态
        isStreaming = true;
        stopRequested = false;

        // 发送消息到流式API - 使用当前选择的模型
        sendMessageToStream(userMessage, currentSessionId, currentModel);
    }
}

// 发送消息到流式API
function sendMessageToStream(userMessage, sessionId, modelType) {
    // 关闭现有连接
    cleanupConnection();

    // 构建URL参数，添加modelType和请求ID
    const params = new URLSearchParams({
        message: userMessage,
        sessionId: sessionId,
        modelType: modelType,
        requestId: currentRequestId
    });

    // 只有在有有效对话ID时才传递conversationId
    if (currentConversationId) {
        params.append('conversationId', currentConversationId);
    }

    // 修改为新的AI服务路径
    const url = `/api/ai/chat/stream?${params.toString()}`;
    console.log('连接URL:', url, '请求ID:', currentRequestId, '模型:', modelType, '对话ID:', currentConversationId);

    eventSource = new EventSource(url);

    // 用于累积完整的消息内容
    let fullMessageContent = '';

    // 开始AI消息流式渲染
    messageRenderer.startAIStream();

    eventSource.onopen = function() {
        console.log('SSE连接已建立，请求ID:', currentRequestId, '模型:', modelType);
        showStatus('连接已建立，等待响应...', 'success');
    };

    eventSource.onmessage = function(event) {
        console.log('收到原始消息:', event.data, '请求ID:', currentRequestId);

        if (event.data === '[DONE]') {
            console.log('流式传输结束标记');
            return;
        }

        try {
            // 解析JSON数据
            const data = JSON.parse(event.data);
            console.log('解析后的消息数据:', data, '请求ID:', currentRequestId);

            // 根据消息类型处理
            if (data.type === 'message' && data.content) {
                // 累积完整消息内容
                fullMessageContent += data.content;

                // 使用新的渲染器更新流式内容
                messageRenderer.updateStreamContent(fullMessageContent);
            } else if (data.type === 'complete') {
                console.log('收到完成事件:', data);
                // 处理完成事件
                handleStreamComplete(data);
            } else if (data.type === 'error') {
                console.error('收到错误事件:', data);
                showStatus('AI响应错误: ' + data.error, 'error');
                finishStream();
            }

        } catch (error) {
            console.error('解析SSE消息失败:', error, '原始数据:', event.data);
            // 如果解析失败，尝试直接作为纯文本处理（向后兼容）
            if (event.data && event.data !== '[DONE]') {
                fullMessageContent += event.data;
                messageRenderer.updateStreamContent(fullMessageContent);
            }
        }
    };

    // 处理特定的事件类型
    eventSource.addEventListener('complete', function(event) {
        try {
            console.log('收到complete事件:', event.data, '请求ID:', currentRequestId);
            if (event.data) {
                const data = JSON.parse(event.data);
                handleStreamComplete(data);
            }
        } catch (error) {
            console.error('解析complete事件失败:', error);
        }
    });

    eventSource.addEventListener('error', function(event) {
        console.error('SSE错误事件:', event, '请求ID:', currentRequestId);

        // 如果不是用户主动停止，才显示错误
        if (!stopRequested) {
            showStatus('连接发生错误', 'error');
        }

        finishStream();
    });

    // 设置超时
    setTimeout(() => {
        if (eventSource && eventSource.readyState === EventSource.OPEN) {
            console.log('请求超时，请求ID:', currentRequestId);
            showStatus('请求超时', 'error');
            finishStream();
        }
    }, 120000);
}

// 处理流式传输完成事件
function handleStreamComplete(data) {
    console.log('处理流式完成事件:', data, '请求ID:', currentRequestId);

    // 处理后端返回的会话ID和对话ID
    if (data.sessionId) {
        currentSessionId = data.sessionId;
        console.log('更新会话ID:', currentSessionId);
    }

    if (data.conversationId) {
        if (!currentConversationId) {
            currentConversationId = data.conversationId;
            console.log('设置当前对话ID:', currentConversationId);

            // 自动生成标题
            const userMessage = document.querySelector('.message.user:last-child .message-content')?.textContent;
            if (userMessage) {
                currentConversationTitle = userMessage.length > 20 ?
                    userMessage.substring(0, 20) + '...' : userMessage;

                // 更新显示
                currentConversationTitleEl.textContent = currentConversationTitle;
            }
        }
    }

    // 处理后端返回的停止状态
    if (data.stopped) {
        console.log('后端确认对话已停止');
        stopRequested = true;
    }

    // 保存状态并更新显示
    saveSessionState();
    updateDisplay();

    finishStream();

    // 刷新对话列表
    setTimeout(() => {
        loadConversations();
    }, 1000);
}

// 完成流式传输
function finishStream() {
    // 使用新的渲染器完成流式渲染
    messageRenderer.finishStream();

    // 重置流式状态
    isStreaming = false;
    stopRequested = false;
    currentRequestId = null; // 清除请求ID

    setButtonState(false);
    hideTypingIndicator();
    userInputEl.disabled = false; // 重新启用输入框
    userInputEl.focus(); // 聚焦到输入框

    // 清理连接
    cleanupConnection();

    // 只有在正常完成时才显示成功状态
    if (!stopRequested) {
        showStatus('对话完成', 'success');
        setTimeout(hideStatus, 2000);
    }

    // 重要：对话完成后保存当前模型状态
    saveSessionState();
}

// 停止流式传输
function stopStream() {
    // 如果已经停止，直接返回
    if (!isStreaming) {
        return;
    }

    console.log('用户请求停止生成，请求ID:', currentRequestId);
    stopRequested = true;

    // 发送停止请求到后端 - 修改为新的对话管理路径
    sendStopRequest();

    // 使用新的渲染器完成流式渲染
    messageRenderer.finishStream();

    // 重置流式状态
    isStreaming = false;
    setButtonState(false);
    hideTypingIndicator();
    userInputEl.disabled = false; // 重新启用输入框
    userInputEl.focus(); // 聚焦到输入框

    // 清理连接
    cleanupConnection();
}

// 清理连接
function cleanupConnection() {
    if (eventSource) {
        eventSource.close();
        eventSource = null;
        console.log('SSE连接已关闭，请求ID:', currentRequestId);
    }
}

// 清理所有资源
function cleanup() {
    cleanupConnection();
    isStreaming = false;
    stopRequested = false;
    currentRequestId = null;
}

// 发送停止请求到后端
function sendStopRequest() {
    if (!currentSessionId) {
        console.warn('没有有效的sessionId，无法发送停止请求');
        return;
    }

    // 修改为新的对话管理路径
    fetch('/api/conversations/stop', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            sessionId: currentSessionId,
            conversationId: currentConversationId,
            requestId: currentRequestId
        })
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                console.log('停止请求发送成功:', data.message);
            } else {
                console.warn('停止请求发送失败:', data.message);
            }
        })
        .catch(error => {
            console.error('发送停止请求失败:', error);
        });
}

// 设置按钮状态
function setButtonState(loading, streaming = false) {
    if (streaming) {
        // 流式传输中，显示停止按钮
        sendBtnEl.disabled = false;
        sendBtnEl.innerHTML = '<i class="bi bi-stop-circle me-1"></i>停止生成';
        sendBtnEl.classList.add('btn-warning');
        sendBtnEl.classList.remove('btn-primary');
    } else if (loading) {
        // 加载中（非流式）
        sendBtnEl.disabled = true;
        sendBtnEl.innerHTML = '<i class="bi bi-hourglass-split me-1"></i>发送中...';
        sendBtnEl.classList.add('btn-primary');
        sendBtnEl.classList.remove('btn-warning');
    } else {
        // 正常状态
        sendBtnEl.disabled = false;
        sendBtnEl.innerHTML = '<i class="bi bi-send me-1"></i>发送';
        sendBtnEl.classList.add('btn-primary');
        sendBtnEl.classList.remove('btn-warning');
    }
}

// 显示/隐藏输入指示器
function showTypingIndicator() {
    typingIndicatorEl.style.display = 'flex';
}

function hideTypingIndicator() {
    typingIndicatorEl.style.display = 'none';
}

// 显示/隐藏状态消息
function showStatus(message, type) {
    statusIndicatorEl.textContent = message;
    statusIndicatorEl.className = `status-indicator ${type}`;
    statusIndicatorEl.style.display = 'block';
}

function hideStatus() {
    statusIndicatorEl.style.display = 'none';
}

// 复制代码块函数
function copyCodeBlock(button) {
    const codeBlock = button.closest('.code-block-wrapper');
    const code = codeBlock.querySelector('code').textContent;
    messageRenderer.copyToClipboard(code, button);
}

// 清空聊天
function clearChat() {
    messageRenderer.clearChat();
    showStatus('对话已清空', 'success');
    setTimeout(hideStatus, 2000);
}

// 响应式设计调整
window.addEventListener('resize', function() {
    if (window.innerWidth > 768) {
        sidebar.classList.remove('open');
        overlay.classList.remove('active');
    }
});